package com.gitee.denger.mybatis.example.ext.analytical;

import com.gitee.denger.mybatis.example.ext.annotation.AndLike;
import com.gitee.denger.mybatis.example.ext.annotation.AndNotLike;
import com.gitee.denger.mybatis.example.ext.util.SimpleReflectionUtils;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

public class ExampleCriteriaValueImpl4Like implements IExampleCriteriaValue {

    /**
     * 匹配符号
     */
    private static final char PERCENT = '%';

    @Override
    public void setForTk(Annotation annotation, Object criteria, String fieldName, Object fieldValue) {
        String methodName = lowerCaseForFirst(annotation.annotationType().getSimpleName());
        Method method = SimpleReflectionUtils.findMethod(criteria.getClass(), methodName, String.class, String.class);
        SimpleReflectionUtils.invokeMethod(method, criteria, fieldName, formatValue(annotation, fieldValue));
    }

    @Override
    public void set(Annotation annotation, Object criteria, String fieldName, Object fieldValue) {
        Method method = SimpleReflectionUtils.findMethod(criteria.getClass(), getMethodName(annotation, fieldName), String.class);
        SimpleReflectionUtils.invokeMethod(method, criteria, formatValue(annotation, fieldValue));
    }

    /**
     * 执行业务
     *
     * @param annotation 使用的注解
     * @param fieldValue 值
     */
    private String formatValue(Annotation annotation, Object fieldValue) {
        Type type;
        if (annotation instanceof AndLike) {
            type = ((AndLike) annotation).type();
        } else if (annotation instanceof AndNotLike) {
            type = ((AndNotLike) annotation).type();
        } else {
            throw new IllegalArgumentException(
                    String.format("%s中没有ExampleCriteriaValueImpl4Like.Type属性，出现错误", annotation.annotationType().getName()));
        }
        //criteria赋值
        StringBuilder fieldValueSb = new StringBuilder();
        switch (type) {
            case all:
                fieldValueSb.append(PERCENT);
                fieldValueSb.append(fieldValue);
                fieldValueSb.append(PERCENT);
                break;
            case prefix:
                fieldValueSb.append(fieldValue);
                fieldValueSb.append(PERCENT);
                break;
            case suffix:
                fieldValueSb.append(PERCENT);
                fieldValueSb.append(fieldValue);
                break;
            default:
                fieldValueSb.append(fieldValue);
                break;
        }
        return fieldValueSb.toString();
    }

    public enum Type {
        /**
         * 全部（%value%）
         */
        all,
        /**
         * 前缀（value%）
         */
        prefix,
        /**
         * 后缀（%value）
         */
        suffix,
        /**
         * 无百分号（value）
         */
        noPercent;
    }
}